<?php

namespace SaasHisApi;

use Exception;
use GuzzleHttp\Client;
use SaasHisApi\Interface\RequestInterface;

class SaasHisClient
{


    public $url = 'https://saas-api.zhimeizhushou.com/';
    public $connectTimeout = 30;
    public $readTimeout = 30;
    public $client;

    public function __construct(Client $client = null)
    {
        if (is_null($client)) {
            $this->client = new Client();
        } else {
            $this->client = $client;
        }
    }

    public function execute(RequestInterface $request, $session = null, $bestUrl = null, $responseType = null)
    {
        //系统参数放入GET请求串
        if ($bestUrl) {
            $requestUrl = $bestUrl;
        } else {
            $requestUrl = $this->url;
        }

        $apiParams = array();
        //获取业务参数
        $apiParams = $request->getParam();

        $headers = [];
        if ($session) {
            $headers['token'] = $session;
        }
        $requestUrl = $requestUrl.$request->getApiName();
        //发起HTTP请求
        if (SaasHisConstant::$METHOD_POST == $request->getApiMethod()) {
            $response = $this->client->post($requestUrl, ['json' => $apiParams, 'headers' => $headers]);
        } else {
            $response = $this->client->get($requestUrl, ['query' => $apiParams, 'headers' => $headers]);
        }

        $code = $response->getStatusCode();
        if ($code != 200) {
            throw new Exception($response->getReasonPhrase(), $code);
        }

        if ($responseType == SaasHisConstant::$RESPONSE_STRING) {
            return $response->getBody();
        } else if ($responseType == SaasHisConstant::$RESPONSE_OBJECT) {
            return json_decode($response->getBody(), true);
        } else {
            return json_decode($response->getBody(), true);
        }
    }
}
